package cn.xiaobai.server;

import cn.xiaobai.domain.ExcelData;
import cn.xiaobai.domain.ExcelImport;
import cn.xiaobai.domain.TablePro;
import cn.xiaobai.listener.ExcelImportListener;
import cn.xiaobai.utils.DBUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 表格工具 服务
 *
 * @Author yangdaji
 * @Date 2024/3/24
 * @PackageName cn.xiaobai.server
 * @ClassName ExcelToolServer
 */
@Slf4j
@Service
public class ExcelToolServer {

    @Autowired
    private DBUtils dbUtils;

    /**
     * 数据导入
     *
     * @param excelImport 表格数据
     * @return
     */
    public TablePro dataImport(ExcelImport excelImport) {
        try {
            ExcelImportListener readListener = new ExcelImportListener();
            EasyExcel.read(excelImport.getFile().getInputStream(), readListener)
                    .excelType(ExcelTypeEnum.XLSX).charset(StandardCharsets.UTF_8).doReadAll();
            ExcelData excelData = readListener.getExcelData();

            // 验证表名
            List<String> tables = dbUtils.showTables("excelTool");
            String tableName = excelImport.getTableName();
            boolean isCreate = false;
            if (StringUtils.isEmpty(tableName)) {
                tableName = "default";
                isCreate = true;
            } else if (!tables.contains(tableName)) {
                isCreate = true;
            }
            if (isCreate) {
                int count = 0;
                // 未指定表名, 默认生成
                if (Objects.equals(tableName, "default")) {
                    while (tables.contains(tableName)) {
                        tableName = "default" + (++count);
                    }
                }
                log.info("确定的表名: {}", tableName);
                // 创建表
                log.info("自动创建表: {}", tableName);
                dbUtils.createTable(tableName, excelData.getHead());
            }

            log.info("{} 数据插入", tableName);
            // 插入数据
            dbUtils.insertData(tableName, excelData.getHead(), excelData.getBody());
            return queryTableByName(tableName);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 表格查询所有, 根据表名
     *
     * @param tableName 表名
     * @return
     */
    public TablePro queryTableByName(String tableName) {

        TablePro tablePro = new TablePro();
        if (StringUtils.isEmpty(tableName)) {
            // 拿第一张表
            List<String> tableAll = getTableAll();
            tableName = tableAll.stream().findFirst().orElse("");
        }

        if (!StringUtils.isEmpty(tableName)) {
            Map<String, Object> dataMap = dbUtils.queryDataByNameOrAll(tableName);
            tablePro.setHead((List<String>) dataMap.get("head"));
            List<List<Object>> body = new ArrayList<>();
            Object bodyO = dataMap.get("body");
            if (bodyO instanceof List<?>) {
                List<?> bodyList = (List<?>) bodyO;
                for (Object o : bodyList) {
                    if (o instanceof Collection<?>) {
                        body.add(new ArrayList<>((Collection<?>) o));
                    }
                }
            }
            tablePro.setBody(body);
            tablePro.setTableName(tableName);
        }
        // 根据表名查询对应的表
        return tablePro;
    }

    /**
     * 获取所有表名
     *
     * @return
     */
    public List<String> getTableAll() {
        return dbUtils.showTables("excelTool");
    }
}
